package com.wangsd.web.mqpay.service;

import com.gitee.fastmybatis.core.query.Query;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.web.mqpay.entity.Merchant;
import com.wangsd.web.mqpay.mapper.MerchantMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MerchantService {
    @Resource
    private MerchantMapper mapper;

    private Merchant selectByName(String name, Long id, String parentCode) {
        Query query = new Query();
        query.eq("name", name);
        query.eq("parent_code", parentCode);
        if (id != null) {
            query.notEq("id", id);
        }
        return mapper.getByQuery(query);
    }

    public List<Merchant> selectPage(Merchant queryObj) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getName())) {
            query.like("name", queryObj.getName());
        }
        if (queryObj.getParentCode() != null) {
            query.eq("parent_code", queryObj.getParentCode());
        }

        List<Merchant> list = mapper.list(query);
        return list;
    }

    public Merchant selectBySubMchId(String subMchId) {
        return mapper.getByColumn("sub_mch_id", subMchId);
    }

    public int saveOrUpdate(Merchant entity) {
        Merchant agent = this.selectByName(entity.getName(), entity.getId(), entity.getParentCode());
        if (agent != null) {
            throw new BusinessException("名称不能重复！");
        }

        if (entity.getId() == null) {
            mapper.saveIgnoreNull(entity);
        } else {
            mapper.updateIgnoreNull(entity);
        }

        return 1;
    }

    public int delete(Long id) {
        return mapper.deleteById(id);
    }

    /**
     * 清零真实金额
     * @param parentCode
     */
    public int resetRealAmount(String parentCode) {
        Query query = new Query().eq("parent_code", parentCode);
        Merchant merchant = new Merchant();
        merchant.setRealAmount(0);
        return mapper.updateByQuery(merchant, query);
    }

    public Merchant selectByReceiveTimeOrder(int payType, String parentCode) {
        List<Merchant> list = mapper.selectByReceiveTimeOrder(payType, parentCode);
        if (list != null)  {
            return list.get(0);
        }
        return null;
    }
}
